package cn.wolfcode.trip.app.controller;


import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * Created by 13925 on 2018/10/28.
 */
@RestController
@RequestMapping("/sessions")
public class SessionsController {

    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     *
     * @RequestParam 表示请求必须携带指定参数:email和password
     */
    @PostMapping
    public JSONResult login(@RequestParam String email, @RequestParam String password, HttpSession session) {
        JSONResult result = new JSONResult();
        //调用业务方法验证用户信息
        User user = userService.getUserByEmailAndPassword(email, password);
        //登录失败
        if (user == null) {
            //返回错误信息
            result.mark("邮箱或者密码错误");
        } else {
            //如果登录成功
            //保存登录令牌(session中添加用户对象)
            session.setAttribute("user_in_session", user);
            result.setResult(user);
        }
        return result;
    }
    @DeleteMapping
    public void logout(HttpSession session) {
        session.invalidate();
    }
}
